﻿using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using Yz.Model.Constants;
using Yz.Model.Views;
using Yz.Mvc.Authentication;
using Yz.Mvc.Controllers;

namespace Yz.Web.Controllers
{
    public class BaseWebController : BaseController
    {
        /// <summary>
        /// 用户头像
        /// </summary>
        protected string UserPhotoPath
        {
            get
            {
                ClaimsIdentity ci = (ClaimsIdentity)User.Identity;
                return ci.FindFirstValue(ClaimTypes.StreetAddress);
            }
        }
        /// <summary>
        /// 学校ID
        /// </summary>
        protected int SchoolId
        {
            get
            {
                ClaimsIdentity ci = (ClaimsIdentity)User.Identity;
                return Convert.ToInt32(ci.FindFirstValue(ClaimTypes.Email));
            }
        }

        protected void SignIn(IList<string> roleList, VmUser user)
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var identity = new ClaimsIdentity(AuthTypes.AppYz);
            Claim Name = new Claim(ClaimTypes.Name, user.UserName);
            Claim NameIdentifier = new Claim(ClaimTypes.NameIdentifier, user.Id.ToString());
            string userPhoto = DefaultConstant.UserPhoto;
            if (!string.IsNullOrEmpty(user.UserPhoto))
            {
                userPhoto = user.UserPhoto;
            }
            Claim Photo = new Claim(ClaimTypes.StreetAddress, userPhoto);
            identity.AddClaim(Name);
            identity.AddClaim(NameIdentifier);
            identity.AddClaim(Photo);
            Claim identityprovider = new Claim(
                "http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider",
                "ASP.NET Identity");
            identity.AddClaim(identityprovider);
            foreach (var role in roleList)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, role));
            }
            AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity);
        }

    }
}